package org.lex.io.utils;

import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Stack;

public class FileUtils {
	public static FileOutputStream openFile(File file) throws IOException {
		boolean exists = createFile(file);
		if (false == exists) {
			System.err.println("Open " + file + " success? " + exists);
		}
		return new FileOutputStream(file);
	}

	public static boolean createFile(File file) throws IOException {
		boolean result = true;
		if (false == file.exists() || false == file.isFile()) {
			result = createFolder(file.getParentFile());
			result = result && file.createNewFile();
		}
		return result;
	}

	public static boolean createFolder(File folder) {
		boolean result = true;
		if (false == folder.exists() || false == folder.isDirectory()) {
			result = folder.mkdirs();
		}
		return result;
	}

	public static Collection<File> listFiles(File folder, FileFilter filter) {
		Stack<File> stack = new Stack<File>();
		stack.push(folder);

		Collection<File> files = new LinkedList<File>();
		if (folder.isFile() && filter.accept(folder)) {
			files.add(folder);
		}
		while (false == stack.isEmpty()) {
			File top = stack.pop();
			File[] children = top.listFiles();
			if (null == children) {
				continue;
			}
			for (File file : children) {
				if (file.isFile() && filter.accept(file)) {
					files.add(file);
				} else {
					stack.push(file);
				}
			}
		}
		return files;
	}
}
